package com.atguigu.edu.realtime.app;

import com.atguigu.edu.realtime.common.Constant;
import com.atguigu.edu.realtime.util.SQLUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

public abstract class BaseAppSql {

    protected abstract void handle(StreamExecutionEnvironment env,StreamTableEnvironment tEnv);

    public void init(int webPort,int parallelism,String groupIdJobNameCKPath){
        //0.0环境获取
        System.setProperty("HADOOP_USER_NAME","atguigu");

        Configuration conf = new Configuration();
        conf.setInteger("rest.port", webPort);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(parallelism);//kafka中主题分区为2，设置并行度和其对应。
        //0.1内部严格一次，checkpoint开启和相关设置
        env.enableCheckpointing(3000);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage(Constant.HDFS_OF_EDU+groupIdJobNameCKPath);
        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);
        //env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);

        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        //给sql APP Job 设置名字
        tEnv.getConfig().getConfiguration().setString("pipeline.name",groupIdJobNameCKPath);

        handle(env,tEnv);

    }

    public void sourceFromOdsDb(StreamTableEnvironment tEnv, String groupId){
        tEnv.executeSql("create table ods_db(\n" +
                "\t`database` string,\n" +
                "\t`table` string,\n" +
                "\t`type` string,\n" +
                "\t`ts` bigint,\n" +
                "\t`data` map<string,string>,\n" +
                "\t`old` map<string,string>,\n" +
                "\t`pt` as proctime()\n" +
                ") "+ SQLUtil.getConnectorKafkaSource(Constant.TOPIC_ODS_DB,groupId));
    }
}
